/**************************************************************
* Copyright (C) 2022 www.eipflow.com 孙泽伟版权所有(盗版必究)
*
* 作者: 孙泽伟(QQ 1039318332)
* 创建时间: 2018/11/9 9:21:04
* 文件名: 
* 描述: 
* 
* 修改历史
* 修改人：
* 时间：
* 修改说明：
*
**************************************************************/
namespace EIP.System.Logic.Impl
{
    /// <summary>
    /// 零代码业务逻辑接口实现
    /// </summary>
    public class SystemZeroCodeDataLogLogic : DapperAsyncLogic<SystemZeroCodeDataLog>, ISystemZeroCodeDataLogLogic
    {
        #region 构造函数
        /// <summary>
        /// 需要建立值和键两个字段
        /// </summary>
        private readonly string[] _relationField = { "radio", "checkbox", "organization", "dictionary", "user", "select", "district", "map", "cascader" };
        /// <summary>
        /// 关联文本
        /// </summary>
        private readonly ISystemZeroCodeLogic _systemZeroCodeLogic;
        private readonly ISystemZeroCodeAutomationLogic _systemZeroCodeAutomationLogic;
        private readonly ISystemWorkSheetLogic _systemWorkSheetLogic;
        /// <summary>
        /// 
        /// </summary>
        public SystemZeroCodeDataLogLogic(
            ISystemZeroCodeLogic systemZeroCodeLogic,
            ISystemZeroCodeAutomationLogic systemZeroCodeAutomationLogic,
            ISystemWorkSheetLogic systemWorkSheetLogic)
        {
            _systemZeroCodeLogic = systemZeroCodeLogic;
            _systemZeroCodeAutomationLogic = systemZeroCodeAutomationLogic;
            _systemWorkSheetLogic = systemWorkSheetLogic;
        }

        #endregion

        #region 方法

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="input">实体</param>
        /// <returns></returns>
        public async Task<OperateStatus> Save(SystemZeroCodeDataLog input)
        {
            OperateStatus operateStatus = new OperateStatus();
            var contents = new List<SystemZeroCodeDataLogContent>();
            if (input.Type == EnumZeroCodeDataLogType.新增.ToShort())
            {
                operateStatus = await InsertAsync(input);
            }
            else if (input.Type == EnumZeroCodeDataLogType.编辑.ToShort())
            {
                SystemDataBaseInput systemDataBaseInput = new SystemDataBaseInput();
                SystemZeroCode zeroCode = new SystemZeroCode();
                using (var fix = new SqlDatabaseFixture())
                {
                    zeroCode = await RedisHelper.CacheShellAsync($"ISystemZeroCodeLogic_Cache:{input.ZeroCodeId}", DateTimeUtil.TotalSeconds(20), async () =>
                    {
                        return await fix.Db.SystemZeroCode.SetSelect(s => new { s.ColumnJson, s.TableName }).FindAsync(f => f.ZeroCodeId == input.ZeroCodeId);
                    });
                }

                var columns = zeroCode.ColumnJson.JsonStringToList<SystemWorkSheetTableFieldDetailInput>();
                var masterBefore = JsonConvert.DeserializeObject<List<SystemZeroCodeDataLogValue>>(input.Before).FirstOrDefault();
                var masterAfter = JsonConvert.DeserializeObject<List<SystemZeroCodeDataLogValue>>(input.After).FirstOrDefault();
                foreach (var item in columns)
                {
                    dynamic beforeValue = null;
                    dynamic afterValue = null;
                    try
                    {
                        var beforeFind = masterBefore.Data.FirstOrDefault(f => f.Key == item.Key);
                        if (!beforeFind.IsNullOrEmpty())
                        {
                            beforeValue = beforeFind.Value;
                        }

                        var afterFind = masterAfter.Data.FirstOrDefault(f => f.Key == item.Key);
                        if (!afterFind.IsNullOrEmpty())
                        {
                            afterValue = afterFind.Value;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                    afterValue = afterValue != null ? afterValue.ToString() : "";
                    beforeValue = beforeValue != null ? beforeValue.ToString() : "";
                    if (beforeValue != afterValue)
                    {
                        contents.Add(new SystemZeroCodeDataLogContent
                        {
                            After = afterValue.ToString(),
                            Before = beforeValue.ToString(),
                            Filed = item.Key,
                            Name = item.Label,
                            Hidden = item.Options.Hidden
                        });
                    }
                    input.Content = JsonConvert.SerializeObject(contents);
                }
                if (contents.Any())
                {
                    operateStatus = await InsertAsync(input);
                }
                if (operateStatus.Code == ResultCode.Success)
                {
                    operateStatus.Msg = "保存成功";
                    await _systemZeroCodeAutomationLogic.AautomationTable(input, contents);
                    List<string> updateSqls = new List<string>();
                    foreach (var item in contents)
                    {
                       await _systemWorkSheetLogic.SetReloadLink(input.ZeroCodeId, item.Filed, input.RowId, item.After, updateSqls);
                    }
                    if (updateSqls.Any())
                    {
                        _systemWorkSheetLogic.SaveDoSqls(updateSqls,null);
                    }
                }
            }
            else if (input.Type == EnumZeroCodeDataLogType.删除.ToShort())
            {
                operateStatus = await InsertAsync(input);
            }
            if (operateStatus.Code == ResultCode.Success)
            {
                operateStatus.Msg = "保存成功";
                await _systemZeroCodeAutomationLogic.AautomationTable(input, contents);
            }
            return operateStatus;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="paging"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperateStatus<List<SystemZeroCodeDataLogFindByRelationOutput>>> FindByRelationId(SystemZeroCodeDataLogFindByRelationInput paging)
        {
            using (var fix = new SqlDatabaseFixture())
            {
                var datas = (await fix.Db.SystemZeroCodeDataLog.SetSelect(s => new { s.Type, s.Content, s.CreateTime, s.CreateUserName, s.CreateUserId }).FindAllAsync(f => f.RowId == paging.RowId)).OrderByDescending(o => o.CreateTime);
                List<SystemZeroCodeDataLogFindByRelationOutput> outputs = new List<SystemZeroCodeDataLogFindByRelationOutput>();
                if (datas.Any())
                {
                    //查找用户头像
                    var userId = datas.Select(s => s.CreateUserId).Distinct().ToList();
                    var user = await fix.Db.SystemUserInfo.SetSelect(s => new { s.HeadImage, s.UserId }).FindAllAsync(f => userId.Contains(f.UserId));
                    foreach (var item in datas)
                    {
                        SystemZeroCodeDataLogFindByRelationOutput systemZeroCodeDataLogFindByRelationOutput = item.MapTo<SystemZeroCodeDataLog, SystemZeroCodeDataLogFindByRelationOutput>();
                        var header = user.FirstOrDefault(f => f.UserId == item.CreateUserId);
                        if (header != null)
                        {
                            systemZeroCodeDataLogFindByRelationOutput.CreateUserHeadImage = header.HeadImage;
                        }
                        outputs.Add(systemZeroCodeDataLogFindByRelationOutput);
                    }
                }
                return OperateStatus<List<SystemZeroCodeDataLogFindByRelationOutput>>.Success(outputs);
            }
        }
        #endregion
    }
}